package com.example.hello.controller;

import com.example.hello.common.Result;
import com.example.hello.dto.PasswordUpdateDTO;
import com.example.hello.dto.UserDTO;
import com.example.hello.entity.User;
import com.example.hello.service.UserService;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Tag(name = "用户管理", description = "用户信息管理相关接口")
@RestController
@RequestMapping("/api/user")
public class UserController {

  @Autowired
  private UserService userService;

  /**
   * 获取当前登录用户信息
   */
  @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的详细信息")
  @ApiResponses(value = {
      @ApiResponse(responseCode = "200", description = "获取成功", 
                   content = @Content(schema = @Schema(implementation = User.class))),
      @ApiResponse(responseCode = "401", description = "未授权")
  })
  @GetMapping("/info")
  public Result<User> getUserInfo() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication.getName();
    User user = userService.getUserByUsername(username);
    
    if (user != null) {
        // 隐藏敏感信息
        user.setPassword(null);
        user.setVerificationCode(null);
        return Result.success(user);
    } else {
        return Result.error(404, "用户不存在");
    }
  }

  /**
   * 根据用户ID获取用户信息
   */
  @Operation(summary = "根据用户ID获取用户信息", description = "根据用户ID获取用户详细信息")
  @ApiResponses(value = {
      @ApiResponse(responseCode = "200", description = "成功获取用户信息"),
      @ApiResponse(responseCode = "404", description = "用户不存在")
  })
  @GetMapping("/{userId}")
  public Result<User> getUserById(
      @Parameter(description = "用户ID", required = true) @PathVariable Long userId) {
    User user = userService.getUserById(userId);
    if (user == null) {
      return Result.error(404, "用户不存在");
    }
    return Result.success(user);
  }

  /**
   * 更新用户基本信息
   */
  @Operation(summary = "更新用户信息", description = "更新当前登录用户的个人信息")
  @ApiResponses(value = {
      @ApiResponse(responseCode = "200", description = "更新成功"),
      @ApiResponse(responseCode = "400", description = "请求参数错误"),
      @ApiResponse(responseCode = "401", description = "未授权")
  })
  @PutMapping("/update")
  public Result<Void> updateUserInfo(
      @Parameter(description = "用户信息", required = true) @RequestBody @Validated UserDTO userDTO) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication.getName();
    User currentUser = userService.getUserByUsername(username);
    
    // 设置用户ID，确保只能修改自己的信息
    userDTO.setUserId(currentUser.getUserId());
    
    boolean success = userService.updateUserInfo(userDTO);
    if (success) {
        return Result.success();
    } else {
        return Result.error(500, "更新用户信息失败");
    }
  }

  /**
   * 修改密码
   */
  @Operation(summary = "修改密码", description = "修改当前登录用户的密码")
  @ApiResponses(value = {
      @ApiResponse(responseCode = "200", description = "密码修改成功"),
      @ApiResponse(responseCode = "400", description = "密码修改失败，原密码错误或新密码不一致")
  })
  @PutMapping("/password")
  public Result<Void> updatePassword(
      @Parameter(description = "密码信息", required = true) @RequestBody @Validated PasswordUpdateDTO passwordUpdateDTO) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication.getName();
    User currentUser = userService.getUserByUsername(username);

    boolean success = userService.updatePassword(currentUser.getUserId(), passwordUpdateDTO);

    if (success) {
      return Result.success();
    } else {
      return Result.error(400, "密码修改失败，请检查原密码是否正确或新密码是否一致");
    }
  }

  /**
   * 分页查询用户列表
   */
  @Operation(summary = "查询用户列表", description = "分页查询用户列表，支持多条件筛选")
  @ApiResponses(value = {
      @ApiResponse(responseCode = "200", description = "查询成功"),
      @ApiResponse(responseCode = "401", description = "未授权")
  })
  @GetMapping("/list")
  public Result<PageInfo<User>> getUserList(
      @Parameter(description = "用户名(模糊查询)") @RequestParam(required = false) String username,
      @Parameter(description = "邮箱(模糊查询)") @RequestParam(required = false) String email,
      @Parameter(description = "手机号(模糊查询)") @RequestParam(required = false) String phone,
      @Parameter(description = "性别(1-男，2-女)") @RequestParam(required = false) Integer gender,
      @Parameter(description = "状态(0-未激活，1-正常，2-禁用)") @RequestParam(required = false) Integer status,
      @Parameter(description = "页码，默认为1") @RequestParam(defaultValue = "1") Integer pageNum,
      @Parameter(description = "每页记录数，默认为10") @RequestParam(defaultValue = "10") Integer pageSize) {
      
      // 构建查询条件
      User user = new User();
      user.setUsername(username);
      user.setEmail(email);
      user.setPhone(phone);
      user.setGender(gender);
      user.setStatus(status);
      
      // 调用服务层方法查询
      PageInfo<User> pageInfo = userService.getUserList(user, pageNum, pageSize);
      
      // 处理返回结果，移除敏感信息
      for (User u : pageInfo.getList()) {
          u.setPassword(null);
          u.setVerificationCode(null);
      }
      
      return Result.success(pageInfo);
  }
}